<?php 

// +----------------------------  公共控制器 ------------------------------------------

namespace app\controller;
use app\BaseController;
use app\common\service\EmailService;
use app\common\service\TokenService;
use app\dto\R;
use app\model\Coupon;
use app\model\Goods;
use app\model\UserCollections;
use app\model\UserCoupons;
use app\model\UserInfos;
use think\facade\Request;
use think\facade\Validate;


class CommonController extends BaseController{

    // 防篡改检查接口
    public function checkOrderInfosReal(){
        // 接收参数：传入商品id，优惠券使用状态，优惠券id，实付价格
        $data = Request::post();

        $goodsId = $data['goodsId'];
        $couponId = $data['couponId'];
        $realPrice = $data['realPrice'];
        $couponStatus = $data['couponStatus'];
        $userId = $data['userId'];

        // 验证一：根据商品id查询商品信息，判断商品是否存在
        $goods = Goods::where('goods_id', $goodsId)->find();
        if (!$goods) {
            return json(R::error("商品不存在"));
        }

        // 优惠券价格：通过查询优惠券信息后获取
        $discountPrice = 0;

        // 检查优惠券是否使用，使用了根据优惠券id查出优惠券信息
        if ($couponStatus == 1) {
            $coupon = Coupon::where('coupon_id', $couponId)->find();
            if (!$coupon) {
                return json(R::error("优惠券不存在"));
            }

            // 检查优惠券是否已经使用
            $userCoupon = UserCoupons::where('user_id', $userId)->where('coupon_id', $couponId)->find();
            if (!$userCoupon) {
                return json(R::error("用户没有领取该优惠券"));
            }

            if ($userCoupon->used == 1) {
                return json(R::error("优惠券已使用"));
            }
            
            // 赋值优惠券价值
            $discountPrice = $coupon->value;
        }

        // 判断商品的实付价格是否被篡改
        // 计算实付价格：商品价格 - 优惠券价值
        $realPriceCheck = $goods->price - $discountPrice;

        if ($realPriceCheck != $realPrice) {
            return json(R::error("实付价格被篡改"));
        }

        // 如果没有被篡改，返回成功
        return json(R::ok("实付价格未被篡改"));

    }

    // 校验传入的Token是否有效
    public function checkToken(){
        $token = Request::post('token');
        if (empty($token)) {
            return json(R::error("Token不能为空"));
        }
        // 验证Token
        $tokenService = new TokenService();
        $checkResult = $tokenService->verifyToken($token);
        if (!$checkResult) {
            return json(R::error("Token无效或登录超时"));
        }else{
            return json(R::ok("Token有效"));
        }
    }

    /**
     * 发送邮箱验证码
     */
    public function sendEmailCode()
    {
        // 接收参数
        $email = Request::post('email');
 
        // 验证邮箱格式
        $validate = Validate::rule([
            'email' => 'require|email'
        ])->message([
            'email.require' => '邮箱不能为空',
            'email.email' => '邮箱格式不正确'
        ]);
        
        if (!$validate->check(['email' => $email])) {
            return json(R::error($validate->getError()));
        }
        
        // 检查邮箱是否已注册 ， 注册也可以发送验证码 ， 用来找回密码
        // $user = UserInfos::where('email', $email)->find();
        // if ($user) {
        //     return json(R::error('邮箱已注册'));
        // }
        
        // 发送验证码
        $emailService = new EmailService();
        $result = $emailService->sendVerificationEmail($email);
        
        return json($result);
    }

    

}